package com.taoyibao.hongcanting.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.event.EventJPushMessage;
import com.taoyibao.hongcanting.model.JPushExtraModel;
import com.taoyibao.hongcanting.ui.MainActivity;
import com.taoyibao.hongcanting.ui.admin.activity.AdministratorActivity;
import com.taoyibao.hongcanting.ui.admin.activity.WaiterActivity;
import com.taoyibao.hongcanting.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import cn.jpush.android.api.JPushInterface;

/**
 * @author TangAnna
 * @description: 极光推送
 * @date :${DATA} 17:12
 */
public class JPushReceiver extends BroadcastReceiver {

    private static final String TAG = "[MyReceiver]";

    /**
     * RegistrationID 定义
     * 集成了 JPush SDK 的应用程序在第一次成功注册到 JPush 服务器时，
     * JPush 服务器会给客户端返回一个唯一的该设备的标识 - RegistrationID。
     * JPush SDK 会以广播的形式发送 RegistrationID 到应用程序。
     * 应用程序可以把此 RegistrationID 保存以自己的应用服务器上，
     * 然后就可以根据 RegistrationID 来向设备推送消息或者通知。
     */
    public static String regId;

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                LogUtils.dNormal(TAG, " 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                LogUtils.dNormal(TAG, " 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                // 对应极光后台的 - 自定义消息  默认不会出现在notification上 所以一般都选用发送通知

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                //用户收到通知
                LogUtils.dNormal(TAG, " 接收到推送下来的通知");

                //先判断消息要给什么身份的用户处理
                if (SpUtils.getLoginStatus() && (SpUtils.getUserType() == CodeConstant.USER_TYPE_SCREEN_OPERATOR ||
                        SpUtils.getUserType() == CodeConstant.USER_TYPE_WAITER)) {//管理员
                    JPushExtraModel jPushExtraModel = getJPushExtraModel(bundle);
                    if (jPushExtraModel != null && jPushExtraModel.code == CodeConstant.JPUSH_EVENT_CODE_100) {
                        //发送消息到屏幕操作员端或者是服务员端进行刷新操作
                        EventJPushMessage message = new EventJPushMessage();
                        message.type = CodeConstant.JPUSH_EVENT_CODE_100;
                        EventBus.getDefault().post(message);
                    }
                } else {
                    //TODO  处理其他通知事件
                }

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {//用户点击打开了通知
                LogUtils.dNormal(TAG, "用户点击打开了通知");
                //TODO 优化页面跳转的逻辑
                //1判断应用是否是在前台

                if (SpUtils.getLoginStatus()) {//已登录
                    if (SpUtils.getUserType() == CodeConstant.USER_TYPE_SCREEN_OPERATOR) {//屏幕操作员

                        Intent intentScreen = new Intent(context, AdministratorActivity.class);
                        intentScreen.putExtras(bundle);
                        intentScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intentScreen);
                    } else if (SpUtils.getUserType() == CodeConstant.USER_TYPE_WAITER) {//服务员

                        Intent intentScreen = new Intent(context, WaiterActivity.class);
                        intentScreen.putExtras(bundle);
                        intentScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intentScreen);
                    } else {

                        Intent intentMain = new Intent(context, MainActivity.class);
                        intentMain.putExtras(bundle);
                        intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intentMain);
                    }
                } else {//未登录
                    Intent intentMain = new Intent(context, MainActivity.class);
                    intentMain.putExtras(bundle);
                    intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intentMain);
                }

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, intent.getAction() + " connected state change to " + connected);
            } else {
                Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印所有的 intent extra 数据
     *
     * @param bundle
     * @return
     */
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }
                sb.append("\nkey:" + key + ", value: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 获取自定义的参数的数据模型
     *
     * @param bundle
     */
    public JPushExtraModel getJPushExtraModel(Bundle bundle) {
        if (!TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
            String result = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Gson gson = new Gson();
            JPushExtraModel jPushExtraModel = gson.fromJson(result, JPushExtraModel.class);
            return jPushExtraModel;
        }
        return null;
    }


}

